package org.jeecg.modules.device;

import org.codehaus.jettison.json.JSONException;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.modules.commu.ClientConnection;
import org.jeecg.modules.commu.ConnectionFactory;
import org.jeecg.modules.driver.DriverPortocal1_0;
import org.jeecg.modules.entity.TigDevice;

/**
 * 设备影子
 */
public class TigDeviceShadow {

    Device device;
    TigDevice tigDeviceEntity;

    public TigDeviceShadow(Device d, TigDevice tdEntity, RabbitMqClient client){
        this.device = d;
        this.tigDeviceEntity = tdEntity;
        ClientConnection conn = ConnectionFactory.ClientConnection(device.getIpAddr(), device.getPort());
        conn.registerRabbitMq(client);
        conn.setDeviceId(device.getId());
        device.setDeviceDriver(new DriverPortocal1_0(device, conn, client));
    }

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public TigDevice getTigDeviceEntity() {
        return tigDeviceEntity;
    }

    public void setTigDeviceEntity(TigDevice tigDeviceEntity) {
        this.tigDeviceEntity = tigDeviceEntity;
    }

    public boolean connect() throws JSONException {

            //if(device != null) {
        boolean ret = true;
        if (!device.getDeviceDriver().getConnection().isConnected())
            ret =  device.getDeviceDriver().getConnection().start();
        else
            ret = true;
        if (ret)
            device.getShadow().getJSONObject("baseinfo").put("isOnline",1);
            //}
        return ret;
    }

    public void disConnect(){

            device.getDeviceDriver().getConnection().disconnect();

    }
}
